import React, { useState, useEffect } from "react";
import apiClient from "../../utils/apiClient";
import "./index.css";

const DocumentDetailPage = ({ kbId, kbName, docId }) => {
  const [document, setDocument] = useState(null);
  const [documentSlices, setDocumentSlices] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState("overview"); // 'overview' or 'slices'

  useEffect(() => {
    setIsLoading(true);
    
    // 使用正确的API路径获取文档详情
    apiClient
      .get(`/documents/${docId}`)
      .then((response) => {
        setDocument(response.data);
      })
      .catch((error) => {
        console.error("Failed to fetch document details:", error);
        alert("加载文档信息失败");
      });

    // 使用正确的API路径获取文档切片
    apiClient
      .get(`/documents/${docId}/slices`)
      .then((response) => {
        setDocumentSlices(response.data);
      })
      .catch((error) => {
        console.error("Failed to fetch document slices:", error);
        setIsLoading(false);
      })
      .catch((error) => {
        console.error("Failed to fetch document slices:", error);
        setDocumentSlices([]);
      })
      .finally(() => setIsLoading(false));
  }, [docId]);

  // 处理空数据情况
  if (!document) {
    return (
      <div className="container empty-state">
        <p>未找到该文档的信息。</p>
        <a href={`#/kb/${kbId}`}>返回知识库</a>
      </div>
    );
  }

  const handleBack = () => {
    window.location.hash = `#/kb/${kbId}`;
  };

  const handleEdit = () => {
    window.location.hash = `#/kb/${kbId}/doc/${docId}/edit`;
  };

  return (
    <div className="container document-detail-page">
      <div className="page-header">
        <div className="header-content">
          <h1>{document.title}</h1>
          <div className="document-meta">
            <span className="meta-item">
              <i className="fas fa-file-alt"></i> {document.fileType}
            </span>
            <span className="meta-item">
              <i className="fas fa-clock"></i> 更新于: {document.lastUpdated}
            </span>
            <span className="meta-item">
              <i className="fas fa-user"></i> 作者: {document.author}
            </span>
            <span className={`status-badge status-${document.status}`}>
              {document.status}
            </span>
          </div>
        </div>
        <div className="header-actions">
          <button
            onClick={handleBack}
            className="secondary"
          >
            <i className="fas fa-arrow-left"></i> 返回知识库
          </button>
          <button
            onClick={handleEdit}
            className="primary"
          >
            <i className="fas fa-edit"></i> 编辑文档
          </button>
        </div>
      </div>

      <div className="document-tabs">
        <button
          className={`tab-button ${activeTab === "overview" ? "active" : ""}`}
          onClick={() => setActiveTab("overview")}
        >
          <i className="fas fa-info-circle"></i> 文档概览
        </button>
        <button
          className={`tab-button ${activeTab === "slices" ? "active" : ""}`}
          onClick={() => setActiveTab("slices")}
        >
          <i className="fas fa-puzzle-piece"></i> 文档切片 (
          {documentSlices.length})
        </button>
      </div>

      <div className="tab-content">
        {activeTab === "overview" ? (
          <div className="overview-tab">
            <div className="document-properties">
              <div className="property-group">
                <h3>文档属性</h3>
                <div className="property-list">
                  <div className="property-item">
                    <span className="property-label">文件类型</span>
                    <span className="property-value">{document.fileType}</span>
                  </div>
                  <div className="property-item">
                    <span className="property-label">文件大小</span>
                    <span className="property-value">{document.fileSize}</span>
                  </div>
                  <div className="property-item">
                    <span className="property-label">页数</span>
                    <span className="property-value">
                      {document.pageCount} 页
                    </span>
                  </div>
                  <div className="property-item">
                    <span className="property-label">创建日期</span>
                    <span className="property-value">{document.createdAt}</span>
                  </div>
                  <div className="property-item">
                    <span className="property-label">最后更新</span>
                    <span className="property-value">
                      {document.lastUpdated}
                    </span>
                  </div>
                  <div className="property-item">
                    <span className="property-label">状态</span>
                    <span className="property-value">
                      <span
                        className={`status-badge status-${document.status}`}
                      >
                        {document.status}
                      </span>
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div className="document-content">
              <h3>文档内容预览</h3>
              <div className="content-preview">
                <p>{document.content}</p>
                <div className="content-placeholder">
                  <i className="fas fa-file-alt"></i>
                  <p>完整内容请下载文档查看</p>
                  <button className="download-btn">
                    <i className="fas fa-download"></i> 下载文档
                  </button>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div className="slices-tab">
            <div className="slices-header">
              <h3>文档切片 - QA 列表</h3>
              <div className="slices-info">
                通过AI从文档中提取的问答对，帮助快速理解文档内容。
              </div>
            </div>
            <div className="qa-list">
              {documentSlices.map((slice, index) => (
                <div key={slice.id} className="qa-item">
                  <div className="qa-question">
                    <span className="qa-number">Q{index + 1}:</span>
                    <span className="question-text">{slice.question}</span>
                  </div>
                  <div className="qa-answer">
                    <span className="qa-number">A{index + 1}:</span>
                    <span className="answer-text">{slice.answer}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default DocumentDetailPage;
